<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <!-- 搜索与添加区域 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getUserList">
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>

        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible = !addDialogVisible"
            >添加用户</el-button
          >
        </el-col>
      </el-row>
      <!-- 用户列表区域 -->
      <el-table :data="userList" stripe border="">
        <el-table-column prop="username" label="姓名"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column prop="mg_state" label="状态">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" active-color="#13ce66" inactive-color="#ff4949" @change="userStateChanged(scope.row)">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180px">
          <template slot-scope="scope">
            <!-- 修改按钮 -->
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.id)"></el-button>
            <!-- 删除按钮 -->
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeUserById(scope.row.id)"></el-button>
            <!-- 带有提示信息的角色分配按钮 -->
            <el-tooltip class="item" effect="dark" content="分配角色" placement="top" :enterable="false">
              <el-button type="warning" icon="el-icon-setting" size="mini" @click="setRole(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="queryInfo.pagenum" :page-sizes="[2, 5, 10]" :page-size="queryInfo.pagesize" layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </el-card>

    <!-- 添加用户对话框 -->
    <el-dialog title="添加用户" :visible.sync="addDialogVisible" width="50%" @close ="addDialogClosed">
      <!-- 表单区域 -->
      <el-form  status-icon label-width="70px" :model="addForm" :rules="addFormRules" ref="addFormRef">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改用户对话框 -->
    <el-dialog title="修改用户" :visible.sync="editDialogVisible" width="50%" @close="editDialogClosed">
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="70px">
        <el-form-item label="用户名" prop="username">
        <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
        <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
        <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUserInfo">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配权限对话框 -->
    <el-dialog title="分配角色" :visible.sync="setRoleDialogVisible" width="50%" @close="setRoleDialogClose">
      <p>当前的用户:{{userInfo.username}}</p>
      <p>当前的角色:{{userInfo.role_name}}</p>
      <p>分配新的角色:
        <el-select v-model="selectedRoleId" placeholder="请选择">
          <el-option v-for="item in this.rolesList" :key="item.id" :label="item.roleName" :value="item.id">
          </el-option>
        </el-select>
      </p>
      <span slot="footer" class="dialog-footer">
      <el-button @click="setRoleDialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="saveRoleInfo">确 定</el-button>
      </span>
    </el-dialog>
    <!--  -->
  </div>
</template>

<script>
export default {
  data() {
    //自定义校验规则函数
    var checkEmail = (rule,value,cb)=>{
      //验证邮箱的正则表达式
      //const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-)]+(\.[a-zA-Z0-9_-])+/ ;
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])/
      if(regEmail.test(value)){
        return cb();
      }
      cb(new Error('请输入合法的邮箱'))
    }

    var checkMobile = (rule,value,cb)=>{
      const regMobile  = /^1(3|4|5|7|8)\d{9}$/;
      if(regMobile.test(value)){
        return cb()
      }
      cb(new Error('请输入正确的手机号'))
    }

    return {
      queryInfo: {
        query: "",
        pagenum: 1,
        pagesize: 7,
      },
      userList: [],
      total: 0,
      //控制添加用户对话框显示和隐藏
      addDialogVisible: false,
      //控制修改用户对话框显示和隐藏
      editDialogVisible:false,
      addForm:{
          username:'',
          password:'',
          email:'',
          mobile:''
      },
      //控制非配角色对话框的显示与隐藏
      setRoleDialogVisible:false,
      //需要分配权限的用户信息
      userInfo:{},
      //所有角色的数据列表
      rolesList:[],
      //当前用户所选的角色
      selectedRoleId:'',
      //自定义校验规则
      addFormRules:{
          username:[
            { required: true, message: "请输入用户名", trigger: "blur" },
            { min: 2, max: 11, message: "长度在 2 到 11 个字符", trigger: "blur" },
          ],
          password:[
            { required: true, message: "请输入密码", trigger: "blur" },
            { min: 6, max: 11, message: "长度在 6 到 11 个字符", trigger: "blur" },
          ],
          email:[{ required: true, message: "请输入邮箱", trigger: "blur" },
            { validator:checkEmail, trigger: "blur" },],
          mobile:[
            { required: true, message: "请输入手机号", trigger: "blur" },
            { validator:checkMobile, trigger: "blur" },
          ]
      },
      //编辑用户信息
      editForm:{
      },
      editFormRules:{
        email:[
          { required: true, message: "请输入邮箱", trigger: "blur" },
            { validator:checkEmail, trigger: "blur" },
        ],
        mobile:[
          { required: true, message: "请输入手机号", trigger: "blur" },
            { validator:checkMobile, trigger: "blur" },
        ]
      },

    };
  },
  mounted() {
    this.getUserList();
  },
  methods: {
    async getUserList() {
      const { data: reslut } = await this.$http.get("users", {
        params: this.queryInfo,
      });
      //   console.log(reslut.data);
      if (reslut.meta.status !== 200)
        return this.$Message.error({
          message: "获取用户列表失败",
          center: true,
        });
      this.$Message.success({ message: "获取用户列表成功", center: true });
      this.userList = reslut.data.users;
      this.total = reslut.data.total;
    },
    //监听pagesize 改变的事件,手动选择事件,每页显示数据条数
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize;
      this.getUserList();
    },
    //监听 页码值的改变事件,当前所处页
    handleCurrentChange(newPage) {
      this.queryInfo.pagenum = newPage;
      this.getUserList();
    },
    //监听switch开关的改变
    async userStateChanged(userinfo){
      const {data:result} =  await this.$http.put(`users/${userinfo.id}/state/${userinfo.mg_state}`);
      if(result.meta.status !==200){
        userinfo.mg_state = !userinfo.mg_state;
        this.$Message.error({message:'用户信息更新失败',center:true})
        return
      }
      this.$Message.success({message:'用户信息更新成功',center:true})
    },
    //监听对话框关闭
    addDialogClosed(){
      this.$refs.addFormRef.resetFields();
    },
    //添加用户信息
    addUser(){
      this.$refs.addFormRef.validate(async valid=>{
        if(!valid) return 
        //添加用户
        const {data:result} = await this.$http.post('users',this.addForm);
        if(result.meta.status !== 201){
          this.$Message.error({message:'添加用户失败!',center:true})
        }
        this.$Message.success({message:'添加用户成功',center:true})
        this.addDialogVisible = false;
        this.getUserList();
      })
    },
    //展示编辑用户对话框
    async showEditDialog(id){
      this.editDialogVisible = true;
      const {data:result} = await this.$http.get('users/'+id);
      if(result.meta.status !== 200){
        return this.$Message.error({message:'查询用户信息失败',center:true})
      }
      this.editForm = result.data;
    },
    editDialogClosed(){
      this.$refs.editFormRef.resetFields()
    },
    //修改用户信息
    editUserInfo(){
      this.$refs.editFormRef.validate(async value=>{
        if(!value) return
        //发起用户修改请求
        const {data:result} = await this.$http.put('users/'+this.editForm.id,{
          email:this.editForm.email,
          mobile:this.editForm.mobile
        })
        if(result.meta.status !== 200){
          return this.$Message.error('修改失败');
        }
        this.editDialogVisible = false;
        this.$Message.success('修改成功');
        this.getUserList();
      })
    },
    //根据id删除用户信息
    async removeUserById(id){
      //弹框询问用户是否删除
      const confimResult = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err=>err)
        if(confimResult !== 'confirm'){
          return this.$Message.info('已取消删除')
        }
        const {data:result}= await this.$http.delete('users/'+id)
        if(result.meta.status !== 200){
          return this.$Message.error('删除用户失败');
        }
        this.$Message.success('删除用户成功')
        this.getUserList();
    },
    //展示分配角色对话框
    async setRole(role){
      this.setRoleDialogVisible = true
      this.userInfo = role
      //展示对话框，获取角色列表
      const {data:result} = await this.$http.get('roles')
      if(result.meta.status !== 200){
        return this.$Message.error('角色列表获取失败');
      }
      this.$Message.success('角色列表获取成功');
      this.rolesList = result.data

    },
    //分配用户角色
    async saveRoleInfo(){
      if(!this.selectedRoleId){
        return this.$Message.error('请选择分配角色')
      }
     const {data:result} =  await this.$http.put(`users/${this.userInfo.id}/role`,{rid:this.selectedRoleId});
     if(result.meta.status !== 200){
       return this.$Message.error('角色分配失败')
     }
     this.$Message.success('角色分配成功')
     this.getUserList();
     this.setRoleDialogVisible = false
    },
    //监听对话框关闭
    setRoleDialogClose(){
      this.selectedRoleId = ''
    }
  },
};
</script>

<style lang="less" scoped>
.el-breadcrumb {
  margin-bottom: 15px;
  font-size: 14px;
}
.el-card {
  box-shadow: 0 1px 1px rgba(0, 0, 0, 0.15);
}
.el-table{
    margin: 10px 0;
}
</style>